package tools;

import core.GlobalConfig;
import core.Main;
import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author dcrm
 */
public class Logger {
    public Date dt = new Date();
    private RandomAccessFile rs;

    /**
     * Start Logger in to file log_dir/log[yyyy.MM.dd].txt
     */
    public Logger() {
        try {
            if (!new File(GlobalConfig.DIR_LOG).exists()) {Main.pr("[Log dir not exist! ."); new File(GlobalConfig.DIR_LOG).mkdir(); Main.pr(".. ("+GlobalConfig.DIR_LOG+") created!]");}
            rs = new RandomAccessFile(GlobalConfig.DIR_LOG+"/log[" + getYMD() + "].txt", "rws");
            rs.seek(rs.length());
        } catch (Exception ex) { writelnErr(ex.getMessage()); }
    }

    /**
     * Return YYYY.MM.DD
     * @return
     */
    public String getYMD() {
        Calendar now = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        String ret= format.format(now.getTime());
        return ret;
    }
    
    /**
     * Write String+date to end logFile
     * @param str
     */
    public void write(String str) { write(str, true); }

    /**
     * Write String to end logFile
     * @param str - Message
     * @param dt - Add date - true/false
     */
    public void write(String str, boolean dt) { FucLib.writeLogUTF8(rs,((dt)?(new Date().toLocaleString()+": "):"")+str); }

    /**
     * Writeln String+date to end logFile
     * @param str
     */
    public void writeln(String str) { writeln(str, true); }

    /**
     * Writeln String to end logFile
     * @param str - Message
     * @param dt - Add date - true/false
     */
    public void writeln(String str, boolean dt) { FucLib.writeLogUTF8(rs,((dt)?(new Date().toLocaleString()+": "):"")+str+"\n"); }

    /**
     * Write String into System.err;
     * @param str
     */
    public static void writeErr(String str) { if (GlobalConfig.F_DEBUG_MSG) System.err.print(str);}

    /**
     * Writeln String into System.err;
     * @param str
     */
    public static void writelnErr(String str) { writeErr(str+"\n"); }

    /**
     * Stop loggind in file
     */
    public void stop() { try { rs.close(); rs=null; } catch (Exception ex) { System.err.println(ex.getMessage()); } }

}
